package com.rytx.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.diagnosis.DiagnosisUtils;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.rytx.common.config.MyAliPayConfig;
import com.rytx.common.config.WxAppConfig;
import com.rytx.common.core.domain.model.ArtUser;
import com.rytx.common.utils.CreateNameUtils;
import com.rytx.common.utils.alipay.AlipayConfigUtil;
import com.rytx.system.domain.vo.ArtUserVo;
import com.rytx.system.service.IArtUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.rytx.common.constant.CacheConstants;
import com.rytx.common.constant.Constants;
import com.rytx.common.constant.UserConstants;
import com.rytx.common.core.domain.entity.SysUser;
import com.rytx.common.core.domain.model.LoginUser;
import com.rytx.common.core.redis.RedisCache;
import com.rytx.common.exception.ServiceException;
import com.rytx.common.exception.user.BlackListException;
import com.rytx.common.exception.user.CaptchaException;
import com.rytx.common.exception.user.CaptchaExpireException;
import com.rytx.common.exception.user.UserNotExistsException;
import com.rytx.common.exception.user.UserPasswordNotMatchException;
import com.rytx.common.utils.DateUtils;
import com.rytx.common.utils.MessageUtils;
import com.rytx.common.utils.StringUtils;
import com.rytx.common.utils.ip.IpUtils;
import com.rytx.framework.manager.AsyncManager;
import com.rytx.framework.manager.factory.AsyncFactory;
import com.rytx.framework.security.context.AuthenticationContextHolder;
import com.rytx.system.service.ISysConfigService;
import com.rytx.system.service.ISysUserService;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 * @author rytx
 */
@Component
public class SysLoginService
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginService.class);
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IArtUserService artUserService;

    @Autowired
    private MyAliPayConfig myAliPayConfig;
    @Autowired
    private WxAppConfig wxAppConfig;
    @Autowired
    private RestTemplate restTemplate;

    private static final String CODE_SUCCESS = "10000";
    private static final String CODE_FAILURE = "20000";
    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }
    public Map<String, Object> wxLogin(String authCode) {
        Map<String, String> wxUserLoginInfo = getWxUserLoginInfo(authCode);
        String openid = wxUserLoginInfo.get("openid");
        HashMap<String, Object> map = new HashMap<>();

        // 保存用户信息
        if(StringUtils.isNotEmpty(openid)) {
            ArtUser user = new ArtUser();
            user.setWxOpenId(openid);
            if(artUserService.selectArtUserList(user).isEmpty()) {
                user.setUserName("YSJ" + CreateNameUtils.getStringRandom(6));
                user.setNickName("匿名用户");
                user.setUserAvatarUrl("");
                user.setWxOpenId(openid);
                user.setUserGender("");
                user.setUserFrom("wx");
                if (artUserService.insertArtUser(user) > 0) {
                    log.info("保存用户信息成功");
                } else {
                    log.info("保存用户信息失败");
                }

            } else {

            }
            //user = artUserService.selectArtUserByAliOpenid(openid);
            user = artUserService.selectArtUserByWxOpenid(openid);
            LoginUser loginUser = new LoginUser(user.getId(),user);
            ArtUserVo artUserVo = new ArtUserVo();
            artUserVo.setUserName(user.getUserName());
            artUserVo.setNikeName(user.getNickName());
            artUserVo.setUserAvatarUrl(user.getUserAvatarUrl());
            artUserVo.setUserGender(user.getUserGender());
            artUserVo.setCity(user.getCity());
            artUserVo.setProvince(user.getProvince());
            artUserVo.setWxOpenId(user.getWxOpenId());
            // 生成token
            String token = tokenService.createToken(loginUser);
            map.put("token", token);
            map.put("user",artUserVo);
        }else {
            log.info("调用失败:{}",wxUserLoginInfo);
            map.put("msg",wxUserLoginInfo);
        }
        return map;

    }
    public Map<String, String> getWxUserLoginInfo(String code) {
        String url ="https://api.weixin.qq.com/sns/jscode2session?appid="+wxAppConfig.getAppId()+
                "&secret="+wxAppConfig.getAppSecret()+"&js_code="+code+"&grant_type=authorization_code";
        String res = restTemplate.getForObject(url,String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        Map<String,String> map = new HashMap<>();
        //获取session_key和openid
        map.put("session_key",jsonObject.getString("session_key"));
        map.put("openid",jsonObject.getString("openid"));
        log.info("getUserInfo:调用成功:{}",res);
        return  map;
    }
    public Map<String, Object> ailLogin( String code) throws AlipayApiException {
        HashMap<String, Object> map = new HashMap<>();
        String gtype = "authorization_code";//授权码方式
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        // 构造请求参数以调用接口
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        if(("authorization_code").equals(gtype)){
            request.setRefreshToken("");//grant_type=authorization_code 不填
            // 设置授权码
            request.setCode(code);//授权码，用户对应用授权后得到。本参数在 grant_type 为 authorization_code 时必填；为 refresh_token 时不填。
            // 设置授权方式
        }else if(("refresh_token").equals(gtype)){
            //TODO 这里需要将上次请求返回的token作为refresh_token 具体操作建议存如redis中时常设置为1小时
            String token = redisCache.getCacheObject("");
            request.setRefreshToken(token);//grant_type=authorization_code 不填
            // 设置授权码
            request.setCode("");//授权码，用户对应用授权后得到。本参数在 grant_type 为 authorization_code 时必填；为 refresh_token 时不填。
        }
        request.setGrantType(gtype);//用授权码来换取授权令牌: authorization_code 或用刷新令牌来换取一个新的授权令牌: refresh_token
        AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
        log.info("getAlipayOAuthToken:调用成功:{}",response.getBody());
        // 调用成功
        if (response.isSuccess()) {
            redisCache.setCacheObject(response.getOpenId(), response.getAccessToken(), 3600, TimeUnit.SECONDS);
            log.info("getAlipayOAuthToken:调用成功:{}",response.getBody());
        } else {
            String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            log.info("诊断链接: {}" , diagnosisUrl);
            map.put("msg",response.getBody());
            return map;
        }

        AlipayClient client = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayUserInfoShareRequest req = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse resp = client.execute(req,response.getAccessToken());
        log.info("getUserInfo:调用成功:{}",resp.getBody());
            // 保存用户信息

        if(resp.isSuccess()&&CODE_SUCCESS.equals(resp.getCode())) {
            ArtUser user = new ArtUser();
            user.setAliOpenId(response.getOpenId());
            if(artUserService.selectArtUserList(user).isEmpty()) {
                user.setUserName("YSJ" + CreateNameUtils.getStringRandom(6));
                user.setNickName(StrUtil.isBlank(resp.getNickName()) ? "匿名用户" : resp.getNickName());
                user.setUserAvatarUrl(resp.getAvatar());
                user.setAliOpenId(resp.getOpenId());
                user.setUserGender(resp.getGender());
                user.setCity(resp.getCity());
                user.setProvince(resp.getProvince());
                user.setUserFrom("ali");
                if (artUserService.insertArtUser(user) > 0) {
                    log.info("保存用户信息成功");
                } else {
                    log.info("保存用户信息失败");
                }

            } else {
//                user.setNickName(StrUtil.isBlank(resp.getNickName()) ? "匿名用户" : resp.getNickName());
//                user.setUserAvatarUrl(resp.getAvatar());
//                user.setAliOpenId(resp.getOpenId());
//                user.setUserGender(resp.getGender());
//                user.setCity(resp.getCity());
//                user.setProvince(resp.getProvince());
//                if (artUserService.updateArtUserByAliOpenid(user) > 0) {
//                    log.info("更新用户信息成功");
//                } else {
//                    log.info("更新用户信息失败");
//                }
            }
            user = artUserService.selectArtUserByAliOpenid(response.getOpenId());
            LoginUser loginUser = new LoginUser(user.getId(),user);
            ArtUserVo artUserVo = new ArtUserVo();
            artUserVo.setUserName(user.getUserName());
            artUserVo.setNikeName(user.getNickName());
            artUserVo.setUserAvatarUrl(user.getUserAvatarUrl());
            artUserVo.setUserGender(user.getUserGender());
            artUserVo.setCity(user.getCity());
            artUserVo.setProvince(user.getProvince());
            artUserVo.setAliOpenId(user.getAliOpenId());
            // 生成token
            String token = tokenService.createToken(loginUser);
            map.put("token", token);
            map.put("user",artUserVo);
        }else {
            log.info("调用失败:{}",response.getBody());
            map.put("msg",response.getBody());
        }
        return map;
    }
    public Map<String, Object> aliLogin( String code) throws AlipayApiException {
        HashMap<String, Object> map = new HashMap<>();
        String gtype = "authorization_code";//授权码方式
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        // 构造请求参数以调用接口
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        if(("authorization_code").equals(gtype)){
            request.setRefreshToken("");//grant_type=authorization_code 不填
            // 设置授权码
            request.setCode(code);//授权码，用户对应用授权后得到。本参数在 grant_type 为 authorization_code 时必填；为 refresh_token 时不填。
            // 设置授权方式
        }
        request.setGrantType(gtype);//用授权码来换取授权令牌: authorization_code 或用刷新令牌来换取一个新的授权令牌: refresh_token
        AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
        log.info("getAlipayOAuthToken:调用成功:{}",response.getBody());
        // 调用成功
        if (response.isSuccess()) {
            redisCache.setCacheObject(response.getOpenId(), response.getAccessToken(), 3600, TimeUnit.SECONDS);
            log.info("getAlipayOAuthToken:调用成功:{}",response.getBody());
        } else {
            String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            log.info("诊断链接: {}" , diagnosisUrl);
            map.put("msg",response.getBody());
            return map;
        }

        //AlipayClient client = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayUserInfoShareRequest req = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse resp = alipayClient.execute(req,response.getAccessToken());
        log.info("getUserInfo:调用成功:{}",resp.getBody());

        ArtUser artUser = artUserService.selectArtUserByAliOpenid(response.getOpenId());
            if(artUser!=null){
            // 保存用户信息
            LoginUser loginUser = new LoginUser(artUser.getId(),artUser);
            String token = tokenService.createToken(loginUser);
            map.put("token", token);
        }else{
            map.put("token", "");
        }
        return map;
    }
    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


}
